﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CookComputing.MetaWeblog;
using CookComputing.XmlRpc;
using System.Configuration;
using System.IO;

namespace myMvcBlog.Infrastructure
{
    public class MetaWeblog : XmlRpcService, IMetaWeblog
    {
        public UserBlog[] getUsersBlogs(string appKey, string username, string password)
        {
            return new UserBlog[] { new UserBlog { blogid = "", blogName = "Jun1st's Notes", url = "http://fengqijun.com" } };
        }

        public object editPost(string postid, string username, string password, CookComputing.MetaWeblog.Post post, bool publish)
        {
            if (Validate(username, password))
            {
                Post oldPost = Post.SingleOrDefault(p => p.ID == long.Parse(postid));
                if (oldPost.ID > 0)
                {
                    return "Post doesn't exists";
                }
                else
                {
                    oldPost.Name = post.title;
                    oldPost.Content = post.description;

                    Post.GetRepo().Update(oldPost);

                    return "Post updated";
                }
            }
            else
            {
                return "Invalid user";
            }
        }

        public CategoryInfo[] getCategories(string blogid, string username, string password)
        {
            if (Validate(username, password))
            {
                int count = Category.All().Count();
                List<Category> cats = Category.All().ToList();
                CategoryInfo[] categories = new CategoryInfo[count];
                for (int i = 0; i < count; i++)
                {
                    categories[i] = new CategoryInfo()
                    {
                        categoryid = cats[i].ID.ToString(),
                        description = cats[i].Name,
                        title = cats[i].Name,
                        rssUrl = cats[i].UrlName,
                        htmlUrl = cats[i].UrlName
                    };
                }

                return categories;
            }
            else
            {
                return null;
            }
        }

        public CookComputing.MetaWeblog.Post getPost(string postid, string username, string password)
        {
            if (Validate(username, password))
            {
                Post post = Post.SingleOrDefault(p => p.ID == long.Parse(postid));

                return new CookComputing.MetaWeblog.Post()
                   {
                       postid = post.ID,
                       description = post.Content
                   };

            }
            else
            {
                return new CookComputing.MetaWeblog.Post();
            }
        }

        public CookComputing.MetaWeblog.Post[] getRecentPosts(string blogid, string username, string password, int numberOfPosts)
        {
            if (Validate(username, password))
            {
                List<Post> posts = Post.All().OrderByDescending(p => p.PostedTime).Take(numberOfPosts).ToList();
                List<CookComputing.MetaWeblog.Post> recentPosts = new List<CookComputing.MetaWeblog.Post>();

                posts.ForEach(post =>
                {
                    recentPosts.Add(
                            new CookComputing.MetaWeblog.Post()
                            {
                                title = post.Name,
                                description = post.Content,
                                mt_excerpt = post.Content,
                                dateCreated = post.PostedTime,
                                categories = (from c in Category.All()
                                              join pt in post.PostCategories on c.ID equals pt.CategoryID
                                              select c.Name).ToArray()
                            }
                        );
                });

                return recentPosts.ToArray();

            }
            else
            {
                return null;
            }
        }

        public string newPost(string blogid, string username, string password, CookComputing.MetaWeblog.Post post, bool publish)
        {
            if (Validate(username, password))
            {
                Post newPost = new Post();
                newPost.Name = post.title;
                newPost.Content = post.description;
                newPost.PostedTime = DateTime.Now;
                newPost.IsPublished = publish;

                var postRepo = Post.GetRepo();
                postRepo.Add(newPost);

                foreach (string cat in post.categories)
                {
                    Category category = Category.SingleOrDefault(c => c.Name == cat);
                    if (category != null && category.ID > 0)
                    {
                        PostCategory.GetRepo().Add(
                                    new PostCategory()
                                    {
                                        PostID = newPost.ID,
                                        CategoryID = category.ID
                                    });

                    }
                }

                return newPost.ID.ToString();
            }
            return string.Empty;
        }

        public UrlData newMediaObject(string blogid, string username, string password, FileData file)
        {
            if (!Validate(username, password))
            {
                throw new XmlRpcFaultException(0, "Login failed");
            }

            string fileName = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath,
                                    "Uploads/Images/" + blogid + "/",
                                    file.name);

            if (!Directory.Exists(Path.GetDirectoryName(fileName)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(fileName));
            }

            File.WriteAllBytes(fileName, file.bits);

            UrlData urldate = new UrlData();
            urldate.url = "http://fengqijun.com/uploads/images" + blogid + "/" + file.name;

            return urldate;
        }

        private bool Validate(string userName, string password)
        {
            if (userName == "jun1st" && password == ConfigurationManager.AppSettings["Password"])
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
